package com.lanren.common.utils;

import android.annotation.SuppressLint;

import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * String工具类
 *
 * @author chengqinhui
 */
@SuppressLint("SimpleDateFormat")
public class StringUtils {

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    public static boolean isNotEmpty(String str) {
        return !StringUtils.isEmpty(str);
    }

    public static boolean isBlank(String str) {
        if (str == null || "".equals(str.trim())) {
            return true;
        }
        return false;
    }

    public static boolean isNotBlank(String str) {
        return !StringUtils.isBlank(str);
    }

    /**
     * 判断是否是手机号码
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        if (mobiles == null || "".equals(mobiles)) {
            return false;
        } else {
            Pattern p = Pattern.compile("^(13|15|18|14)\\d{9}$");
            Matcher m = p.matcher(mobiles);
            return m.matches();
        }
    }

    /**
     * 在给定的字符串中，用新的字符替换所有旧的字符
     *
     * @param string  给定的字符串
     * @param oldchar 旧的字符
     * @param newchar 新的字符
     * @return 替换后的字符串
     */
    public static String replace(String string, char oldchar, char newchar) {
        char chars[] = string.toCharArray();
        for (int w = 0; w < chars.length; w++) {
            if (chars[w] == oldchar) {
                chars[w] = newchar;
                break;
            }
        }
        return new String(chars);
    }

    /**
     * 判断是否是邮箱
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (email == null || "".equals(email)) {
            return false;
        } else {
            String rule = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
            Pattern pattern;
            Matcher matcher;
            pattern = Pattern.compile(rule);
            matcher = pattern.matcher(email);
            if (matcher.matches()) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 判断是否是身份证
     *
     * @param idCard
     * @return
     */
    public static boolean isIdCard(String idCard) {
        if (idCard == null || "".equals(idCard)) {
            return false;
        } else {
            Pattern p = Pattern.compile("\\d{15}|\\d{18}");
            Matcher m = p.matcher(idCard);
            return m.matches();
        }
    }

    public static boolean isTelephone(String idCard) {
        if (idCard == null || "".equals(idCard)) {
            return false;
        } else {
            Pattern p = Pattern.compile("\\d{3}-\\d{8}|\\d{4}-\\d{7}");
            Matcher m = p.matcher(idCard);
            return m.matches();
        }
    }


    /**
     * 分解字符串，并且剔除空的元素。
     *
     * @param str
     * @param regex
     * @return
     */
    public static List<String> split2list(String str, String regex) {
        List<String> retList = new ArrayList<String>();
        if (str == null) {
            return retList;
        }
        String[] words = str.split(regex);
        for (int i = 0; i < words.length; i++) {
            if ((words[i] != null)
                    && (!words[i].trim().equals(""))
                    ) {
                retList.add(words[i]);
            }
        }
        return retList;
    }

    /**
     * 只允许字母、数字
     *
     * @param str
     * @return
     */
    public static String stringFilter(String str) {
        // 只允许字母、数字和汉字
//        String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";
        String regEx = "[^a-zA-Z0-9@.]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }
    /**
     * 只允许字母、数字和汉字
     *
     * @param str
     * @return
     */
    public static String stringFilterC(String str) {
        // 只允许字母、数字和汉字
        String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";
//        String regEx = "[^a-zA-Z0-9@.]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 判断是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 判断是否是拼音
     *
     * @param str
     * @return
     */
    public static boolean isPinYin(String str) {
        Pattern pattern = Pattern.compile("[ a-zA-Z]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 判断是否是中文
     *
     * @param str
     * @return
     */
    public static boolean containCn(String str) {
        Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]");
        return pattern.matcher(str).find();
    }

    /**
     * 以空字符串取代null
     *
     * @param str
     * @return
     */
    public static String replaceNullByBlank(String str) {
        if (str == null || "null".equals(str) || "".equals(str)) {
            return "";
        }
        return str;
    }

    /**
     * 以 - 取代null
     *
     * @param str
     * @return
     */
    public static String replaceLineByBlank(String str) {
        if (str == null || "null".equals(str) || "".equals(str)) {
            return "-";
        }
        return str;
    }

    /**
     * 以pstr来代替null
     *
     * @param str
     * @param pstr
     * @return
     */
    public static String replaceNullByPstr(String str, String pstr) {
        if (str == null || "null".equals(str) || "".equals(str)) {
            return pstr;
        }
        return str;
    }

    /********
     * 设置对象属性值
     *
     * @param declaredField
     * @param o1
     * @param o2
     * @throws SecurityException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     */
    public static Object setField(String declaredField, Object o1, Object o2)
            throws SecurityException, IllegalArgumentException,
            IllegalAccessException, InvocationTargetException,
            NoSuchMethodException {
        if (o1 == null)
            return null;
        return o1
                .getClass()
                .getMethod("set" + changeFirstToLarge(declaredField),
                        o2.getClass()).invoke(o1, o2);
    }

    /*****
     * 取得对象属性值
     *
     * @param declaredField
     * @param o1
     * @param o1
     * @throws SecurityException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     */
    public static Object getField(String declaredField, Object o1)
            throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException,
            InvocationTargetException, NoSuchMethodException {
        if (o1 == null)
            return null;
        return o1.getClass()
                .getMethod("get" + changeFirstToLarge(declaredField))
                .invoke(o1);
    }

    @SuppressLint("DefaultLocale")
    public static String changeFirstToLarge(String val) {
        if ("".equals(val))
            return val;
        return val.substring(0, 1).toUpperCase()
                + val.substring(1, val.length());
    }

    public static String getNowTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar
                .getInstance().getTime());
    }

    public static String getNowTime(String format) {
        return new SimpleDateFormat(format).format(Calendar.getInstance()
                .getTime());
    }

    public static String getNowTime(String data, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date date = sdf.parse(data);
            return sdf.format(date);
        } catch (ParseException e) {
            return data;
        }
    }

    /**
     * 判断字符串是否存在数组中
     *
     * @param filters
     * @param filter
     * @return
     */
    public static boolean isContainedItem(String[] filters, String filter) {
        if (filters == null || filters.length == 0) {
            return false;
        }

        for (int i = 0, len = filters.length; i < len; i++) {
            String tmpFilter = filters[i];
            if (tmpFilter.equals(filter)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 当不需要单位时，str为null或空时，用pstr代替，返回pstr；如果需要显示单位，就显示数据值+单位，返回str+unit
     *
     * @param str  从数据库里获取的数据，可能为null,可能为"",可能为具体的值
     * @param pstr 为null或空时需要被替换成的字符串,比如"无", "0", ""
     * @param unit 单位(有单位的)
     * @return
     */
    public static String replaceNullByPstrAddUnit(String str, String pstr, String unit) {
        if (str == null || "null".equals(str) || "".equals(str)) {
            return pstr;
        }
        return str + unit;
    }

    public static boolean doubleIsNull(Double value) {
        if (value == 0.0) {
            return true;
        }
        return false;
    }

    public static String doubleIsNullByPstr(Double value, String pstr) {
        if (value == 0.0) {
            return pstr;
        }
        return value + "";
    }

    public static String doubleIsNullByPstrAddUnit(Double value, String pstr, String unit) {
        if (value == 0.0) {
            return pstr;
        }
        return value + unit;
    }

    public static boolean intIsNull(int value) {
        if (value == 0 || value == -1) {
            return true;
        }
        return false;
    }

    public static String intIsNullByPstr(int value, String pstr) {
        if (value == 0 || value == -1) {
            return pstr;
        }
        return value + "";
    }

    public static String intIsNullByPstrAddUnit(int value, String pstr, String unit) {
        if (value == 0 || value == -1) {
            return pstr;
        }
        return value + unit;
    }

    /**
     * 格式时间字符窜
     *
     * @param str    字符窜
     * @param format 格式
     * @return
     */
    public static String formatDateStr(String str, String format, String format2) {
        try {
            SimpleDateFormat format1 = new SimpleDateFormat(format);
            return new SimpleDateFormat(format2).format(format1.parse(str));
        } catch (ParseException e) {
            return str;
        }
    }

    /**
     * 把时间格式化数组
     *
     * @param date yyyy-MM-dd
     * @return
     */
    public static int[] splitDate(String date) {
        boolean flag = false;
        if (date == null) flag = true;
        String[] strs = date.split("-");
        int[] dates = new int[3];
        if (strs.length == 3) {
            for (int i = 0; i < strs.length; i++) {
                try {
                    dates[i] = Integer.parseInt(strs[i]);
                } catch (Exception e) {
                    flag = true;
                    break;
                }
            }
        } else flag = true;

        if (flag) {
            Calendar c = Calendar.getInstance();
            dates[0] = c.get(Calendar.YEAR);
            dates[1] = c.get(Calendar.MONTH);
            dates[2] = c.get(Calendar.DAY_OF_MONTH);
        }
        return dates;
    }

    /**
     * 格式为#.########
     */
    public static String formatDouble(double amount) {
        if (amount == 0 || amount == 0.0) {
            return "";
        }
        NumberFormat nf = NumberFormat.getCurrencyInstance();
        DecimalFormat df = (DecimalFormat) nf;
        df.setMinimumFractionDigits(2);
        df.setMaximumFractionDigits(2);
        df.setDecimalSeparatorAlwaysShown(true);
        String pattern = "#.########";
        df.applyPattern(pattern);

        String ret = df.format(amount);

        return ret;
    }

    public static String formatDouble(double amount, String format) {
        if (amount == 0 || amount == 0.0) {
            return "";
        }
        NumberFormat nf = NumberFormat.getCurrencyInstance();
        DecimalFormat df = (DecimalFormat) nf;
        df.setMinimumFractionDigits(2);
        df.setMaximumFractionDigits(2);
        df.setDecimalSeparatorAlwaysShown(true);
        String pattern = format;
        df.applyPattern(pattern);

        String ret = df.format(amount);

        return ret;
    }

    /***
     * 数量四舍五入
     * @param qty 需要舍入的数量
     * @return 精确后的结果
     */
    public static double weightDigit(Double qty) {
        if (qty == null) {
            return 0.0;
        } else {
            return Math.round(qty * Math.pow(10, 3)) / Math.pow(10, 3);
        }
    }

    /***
     *格式化质检值
     *@param value 需要格式化的值
     *@param decimals 保留小数位数
     */
    public static String formatQcValue(String value, String decimals) {
        String result = null;
        String str = "#.#";
        if (decimals.equals("") || decimals == null) {
            decimals = "0";
        }
        if (value == null || value.equals("") ) {
            result = "0";
        } else {
            if (!decimals.equals("0")) {
                for (int i = 1; i < Integer.parseInt(decimals); i++) {
                    str += "#";
                }
            }
            DecimalFormat df = new DecimalFormat(str);
            result = df.format(Double.parseDouble(value));
        }
        return result;
    }

    public static String formatNum(double num) {
        String unit = "";
        if (num >= 10000) {
            unit = "万";
            num = num / 10000;
        }
        return formatDouble(num, "0.00") + unit;
    }

    /**
     * 格式化日期控件值 yyyy-MM-dd
     *
     * @param year
     * @param month
     * @param dayOfMonth
     */
    public static String fromatDatePicker(int year, int month, int dayOfMonth) {
        String mm = "";
        String dd = "";
        month += 1;
        if (month <= 9) {
            mm = "0" + month;
        } else {
            mm = String.valueOf(month);
        }
        if (dayOfMonth <= 9) {
            dd = "0" + dayOfMonth;
        } else {
            dd = String.valueOf(dayOfMonth);
        }
        return year + "-" + mm + "-" + dd;
    }

    /**
     * 格式化时间控件  00:00
     *
     * @param hour
     * @param minute
     * @return
     */
    public static String fromatTimePicker(int hour, int minute) {
        String hh = "";
        String mm = "";
        if (hour <= 9) {
            hh = "0" + hour;
        } else {
            hh = String.valueOf(hour);
        }
        if (minute <= 9) {
            mm = "0" + minute;
        } else {
            mm = String.valueOf(minute);
        }
        return hh + ":" + mm;
    }

    /**
     * 拆分条件  拆分数字
     *
     * @param con
     * @return
     */
    public static List<String> genNumStr(String con) {
        List<String> keys = new ArrayList<String>(0);
        if (!StringUtils.isEmpty(con)) {
            char[] strs = con.toCharArray();
            boolean isNum = true;
            StringBuffer sb = new StringBuffer("");
            for (int i = 0; i < strs.length; i++) {
                int str = strs[i];
                if (str >= 65 && str <= 91) {
                    isNum = false;
                } else if (str >= 48 && str <= 57 || str == 46) {
                    if (isNum) {
                        sb.append(strs[i]);
                    }
                } else if (!(str >= 48 && str <= 57)) {
                    if (sb.length() > 0) keys.add(sb.toString());
                    sb = new StringBuffer("");
                    isNum = true;
                }
                if (i == strs.length - 1) {
                    if (sb.length() > 0) keys.add(sb.toString());
                }
            }
        }
        return keys;
    }

    /**
     * 拆分条件 拆分条件文本
     *
     * @param con
     * @return
     */
    public static List<String> genConTextStr(String con) {
        List<String> keys = new ArrayList<String>(0);
        String regEx1 = "([1-9]+[0-9]*|0)(\\.[\\d]+)?";
        if (!StringUtils.isEmpty(con)) {
            con = con.replaceAll("([1-9]+[0-9]*|0)(\\.[\\d]+)?", "#");
            System.out.println(con);
            if (con.indexOf("#") != -1) {
                String[] ss = con.split("#");
                for (String item : ss) {
                    keys.add(item);
                }
            }

        }
        return keys;
    }

    /**
     * 拆分条件 拆分条件表达式
     *
     * @param con
     * @return
     */
    public static List<String> genConStr(String con) {
        List<String> keys = new ArrayList<String>(0);
        if (!StringUtils.isEmpty(con)) {
            char[] strs = con.toCharArray();
            boolean isText = false;
            StringBuffer sb = new StringBuffer("");
            for (int i = 0; i < strs.length; i++) {
                int str = strs[i];
                if (str >= 65 && str <= 91) {
                    isText = true;
                    sb.append(strs[i]);
                } else if (str >= 48 && str <= 57 || str == 46) {
                    if (isText) {
                        sb.append(strs[i]);
                    } else {
                        if (sb.length() > 0) keys.add(sb.toString());
                        sb = new StringBuffer("");
                        isText = false;
                    }
                } else if (!(str >= 48 && str <= 57)) {
                    sb.append(strs[i]);
                    isText = false;
                }
                if (i == strs.length - 1) {
                    if (sb.length() > 0) keys.add(sb.toString());
                }
            }
        }
        return keys;
    }

    /**
     * 分钟 转化为时间文本   （3天12小时56分）
     *
     * @param exMinute
     * @return
     * @author lwj
     */
    public static String castTimeDetail(Long exMinute) {
        String str = "";
        if (exMinute < 0) {
            return str;
        }
        int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;

        long day = exMinute / dd;
        long hour = (exMinute - day * dd) / hh;
        long minute = (exMinute - day * dd - hour * hh) / mi;

        return (day > 0 ? day + "天" : "") + (hour > 0 ? hour + "小时" : "") + (minute > 0 ? minute
                + "分钟" : "");
    }
}
